const UserBo = require("../bo/user-bo");
const {request} = require("../utils/request");
const {getDaysBetweenDates,dateDiffWithNumber,isCurrentDay,diifTime} = require("../utils/date");
const UserRecordMapper = require("../database/mapper/user-record")
const {retry, utf16ToUtf8} = require("../utils/fun");
const {sleep} = require("ee-bin/tools/serve");
const Log = require('ee-core/log');

module.exports = class RedPacketBo extends UserBo{

    roleLevel = 80
    registered_at = ""
    user_id = 0
    pwd = ""
    recharge_money = 0

    taskMap = {}

    init(){
        this.userRecordMapper = new UserRecordMapper()
    }
    setRegisteredAt(at){
        this.registered_at = at
        return this
    }
    setUserId(id){
        this.user_id = id
        return this
    }
    setPwd(pwd){
        this.pwd = pwd
        return this
    }
    setRechargeMoney(money){
        this.recharge_money = money
        return this
    }
    setSender(sender){
        this.sender = sender
    }

    async getList(){
        let params = Object.assign(this.getCommonParams(),{
            status: "1,2,4",
            roleLevel: this.roleLevel
        })
        let ret = await request({
            url: '/api/api.php/protocol/101012',
            method: 'post',
            responseType:'json',
            formData:params,
            headers:this.headers
        })

        if(!ret){
            throw new Error("列表获取失败")
        }
        if(ret.status!==200){
            throw new Error(ret.msg)
        }
        let redEnvelopList = ret['data']['red_envelop_list']
        let map = {}
        for (let red of redEnvelopList){
            if(isCurrentDay(red['re_start_time']) && !this.isOver(red)){
                let type = this.getType(red)
                if(map[type]){
                    map[type].push(red)
                }else{
                    map[type] = [red]
                }
            }
        }
        return map
    }


    getType(red){
        for(let cond of red['condition_desc_list']) {
            if(cond['desc'].includes("24小时")){
                return  '24H'
            }
            if(cond['desc'].includes("3天")){
                return '3D'
            }
            if(cond['desc'].includes("7天")){
                return '7D'
            }
            if(cond['desc'].includes("188")){
                return '0'
            }
        }
        return "other"
    }

    // 红包是否领取完
    isOver(red){
        return red['num']  == red['receive_num']
    }


    receiveByMps(maps){
        for(let key in maps){
            let list = maps[key]
            for (let red of list){
                if(!isCurrentDay(red['re_start_time'])){
                    console.log("not red")
                    // 只领取今天的
                    continue
                } else if(key == '24H' && dateDiffWithNumber(this.registered_at,red['re_start_time'], 1)){
                    //24小时内可以领取
                    this.receiveTask(red)
                }
                else if(key == '3D' && dateDiffWithNumber(this.registered_at,red['re_start_time'], 3)){
                    //3天内可以领取
                    this.receiveTask(red)
                }
                else if(key == '7D' && dateDiffWithNumber(this.registered_at,red['re_start_time'], 7)){
                    //7天内可以领取
                    this.receiveTask(red)
                }
                else if(key == '0'){
                    //无限制
                    this.receiveTask(red)
                }else{
                    console.log("没有可领取的红包")
                }
            }
        }

    }
    is_repeat(red){
        return this.userRecordMapper.count({
            user_id: this.user_id
            ,red_id: red['id']
        }) > 0
    }

    async receiveTask(red) {
       if(red['id'] in this.taskMap){
           console.log("任务已重复！")
           return
       }
       this.taskMap[red['id']] = 1
        if(this.recharge_money == 0){
            console.log("没有充值，不可领取红包")
            return
        }
        if (this.is_repeat(red)) {
            return false
        }
        let diff = diifTime(red['re_start_time']) > 0 ? diifTime(red['re_start_time']) : 0

        console.log(this.userName+":创建红包任务")
        setTimeout(async () => {
            await this.retryReceive(red)
        }, diff)


    }
    async retryReceive(red){
        await retry(async () => {
            let ret = this.receive(red)
            if (ret === false) {
                await sleep(500)
            }
            return ret
        })
    }

    async receive(red){
        console.log(this.userName+":开始领取红包->" + red['id'])
        let params = Object.assign(this.getCommonParams(),{
            'redEnvelopId': red['id']
        })
        if(red['need_countersign'] == 1){
            params['countersign'] = this.pwd
        }
        try {
            let ret = await request({
                url: '/api/api.php/protocol/101013',
                method: 'post',
                responseType: 'json',
                formData: params,
                headers: this.headers
            })
            console.log(this.userName+":领取红包" )
            console.log(ret)
            if (ret['status'] == 200) {
                await this.userRecordMapper.create({
                    user_id: this.user_id,
                    red_id: red['id'],
                    money: ret['data']['receive_money']
                })
                return true
            }
            return false
        }catch (e){
            console.log(e)
        }
    }
}